var that
var num = 3
class tab {
  constructor(id) {
    this.main = document.querySelector(id)
    // console.log(typeof(id));
    this.addBtn = this.main.querySelector('.tabadd')
    this.ul = this.main.querySelector('ul')
    this.tabscon = this.main.querySelector('.tabscon')

    that = this
    this.init()
  }
  // 初始化
  init() {
    this.fresh()
    for (var i = 0; i < this.lis.length; i++) {
      this.lis[i].index = i
      this.lis[i].onclick = this.doToggle
      this.removeBtn[i].onclick = this.removeTab
      this.changes[i].ondblclick = this.changeText
      this.sections[i].ondblclick = this.changeText
    }
    this.addBtn.onclick = this.add
  }
  // 重新获取对象
  fresh() {
    this.lis = this.main.querySelectorAll('li')
    this.sections = this.main.querySelectorAll('section')
    this.removeBtn = this.main.querySelectorAll('.iconfont')
    this.changes = this.main.querySelectorAll('ul li span:first-child')
    // console.log(this.removeBtn)
  }
  // 改
  doToggle() {
    that.pai()
    this.className = 'liactive'
    that.sections[this.index].className = 'conactive'
  }
  //   排他
  pai() {
    for (var i = 0; i < this.lis.length; i++) {
      this.lis[i].className = ''
      this.sections[i].className = ''
    }
  }
  // 增
  add() {
    that.pai()
    num++
    var li =
      '<li class="liactive"><span>测试' +
      num +
      '</span><span class="iconfont icon-guanbi"></span></li>'
    var section = '<section class="conactive">测试' + num + '</section>'
    that.ul.insertAdjacentHTML('beforeend', li)
    that.tabscon.insertAdjacentHTML('beforeend', section)
    that.init()
  }
  //   删
  removeTab(e) {
    e.stopPropagation()
    var index = this.parentNode.index
    // console.log(index)
    that.lis[index].remove()
    that.sections[index].remove()
    that.init()
    // that.fresh()
    // console.log(that.main.querySelector('.liactive'))
    if (document.querySelector('.liactive')) return
    index--

    index = index < 0 ? 0 : index
    that.lis[index] && that.lis[index].click()

    // that.lis[index].click()
  }
  //    改
  changeText() {
    var str = this.innerHTML
    // 双击禁止选定文字
    this.innerHTML = '<input type="text">'
    var input = this.children[0]
    input.value = str
    input.select()
    input.onblur = function () {
      this.parentNode.innerHTML = input.value
    }
    input.onkeyup = function (e) {
      if (e.keyCode == 13) this.blur()
    }
  }
}
var tab1 = new tab('#tab')
